<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单功能测试</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <h1>简单功能测试</h1>
        
        <div class="alert alert-info">
            <strong>说明：</strong>这是一个简化的测试页面，用于测试导出、查看详情和处理历史功能。
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>登录</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" value="admin">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">密码</label>
                            <input type="password" class="form-control" id="password" value="admin123">
                        </div>
                        <button class="btn btn-primary" id="loginBtn">登录</button>
                        <span id="loginStatus" class="ms-2"></span>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>功能测试</h5>
                    </div>
                    <div class="card-body">
                        <button class="btn btn-success mb-2 w-100" id="testExportBtn" disabled>测试导出功能</button>
                        <button class="btn btn-info mb-2 w-100" id="testDetailBtn" disabled>测试查看详情</button>
                        <button class="btn btn-warning mb-2 w-100" id="testHistoryBtn" disabled>测试处理历史</button>
                        <button class="btn btn-secondary mb-2 w-100" id="testListBtn" disabled>测试获取列表</button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5>输出日志</h5>
                        <button class="btn btn-sm btn-outline-secondary" id="clearLogBtn">清空日志</button>
                    </div>
                    <div class="card-body">
                        <pre id="logOutput" style="max-height: 400px; overflow-y: auto; background: #f8f9fa; padding: 15px; font-size: 12px;"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let adminToken = null;
        
        // 日志函数
        function log(message, type = 'info') {
            const output = document.getElementById('logOutput');
            const timestamp = new Date().toLocaleTimeString();
            const prefix = type === 'error' ? '❌' : type === 'success' ? '✅' : 'ℹ️';
            output.textContent += `${prefix} [${timestamp}] ${message}\n`;
            output.scrollTop = output.scrollHeight;
            console.log(`[${type}]`, message);
        }
        
        // 清空日志
        function clearLog() {
            document.getElementById('logOutput').textContent = '';
        }
        
        // 登录功能
        async function login() {
            try {
                log('开始登录...');
                const username = document.getElementById('username').value;
                const password = document.getElementById('password').value;
                
                const response = await fetch('/api/admin/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                const result = await response.json();
                
                if (response.ok && result.data && result.data.token) {
                    adminToken = result.data.token;
                    localStorage.setItem('adminToken', adminToken);
                    log('登录成功！', 'success');
                    document.getElementById('loginStatus').innerHTML = '<span class="text-success">✅ 已登录</span>';
                    
                    // 启用功能按钮
                    document.getElementById('testExportBtn').disabled = false;
                    document.getElementById('testDetailBtn').disabled = false;
                    document.getElementById('testHistoryBtn').disabled = false;
                    document.getElementById('testListBtn').disabled = false;
                } else {
                    log(`登录失败: ${result.message}`, 'error');
                    document.getElementById('loginStatus').innerHTML = '<span class="text-danger">❌ 登录失败</span>';
                }
            } catch (error) {
                log(`登录错误: ${error.message}`, 'error');
                document.getElementById('loginStatus').innerHTML = '<span class="text-danger">❌ 网络错误</span>';
            }
        }
        
        // 测试导出功能
        async function testExport() {
            try {
                log('开始测试导出功能...');
                
                if (!adminToken) {
                    log('请先登录', 'error');
                    return;
                }
                
                // 构建导出URL
                const params = new URLSearchParams({
                    format: 'excel',
                    clue_ids: '1,2' // 测试导出ID为1和2的线索
                });
                
                const exportUrl = `/api/admin/clues/export?${params}&token=${encodeURIComponent(adminToken)}`;
                log(`导出URL: ${exportUrl}`);
                
                // 先测试API响应
                const testResponse = await fetch(exportUrl, {
                    method: 'HEAD' // 只获取头部信息，不下载文件
                });
                
                log(`API响应状态: ${testResponse.status}`);
                log(`Content-Type: ${testResponse.headers.get('Content-Type')}`);
                
                if (testResponse.ok) {
                    log('API响应正常，开始下载...', 'success');
                    
                    // 创建下载链接
                    const link = document.createElement('a');
                    link.href = exportUrl;
                    link.download = `线索导出_${new Date().toISOString().slice(0, 10)}.xls`;
                    link.style.display = 'none';
                    
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    
                    log('下载已触发', 'success');
                } else {
                    const errorText = await testResponse.text();
                    log(`导出失败: ${testResponse.status} - ${errorText}`, 'error');
                }
                
            } catch (error) {
                log(`导出错误: ${error.message}`, 'error');
            }
        }
        
        // 测试查看详情
        async function testDetail() {
            try {
                log('开始测试查看详情...');
                
                if (!adminToken) {
                    log('请先登录', 'error');
                    return;
                }
                
                const clueId = 1; // 测试线索ID 1
                const response = await fetch(`/api/admin/clues/${clueId}`, {
                    headers: {
                        'Authorization': `Bearer ${adminToken}`
                    }
                });
                
                log(`详情API响应状态: ${response.status}`);
                
                if (response.ok) {
                    const result = await response.json();
                    log(`获取线索详情成功: ${result.data.title || '无标题'}`, 'success');
                    log(`线索编号: ${result.data.clue_no}`);
                    log(`线索状态: ${result.data.status}`);
                } else {
                    const errorText = await response.text();
                    log(`获取详情失败: ${response.status} - ${errorText}`, 'error');
                }
                
            } catch (error) {
                log(`详情查看错误: ${error.message}`, 'error');
            }
        }
        
        // 测试处理历史
        async function testHistory() {
            try {
                log('开始测试处理历史...');
                
                if (!adminToken) {
                    log('请先登录', 'error');
                    return;
                }
                
                const clueId = 1; // 测试线索ID 1
                const response = await fetch(`/api/admin/clues/${clueId}/processing-history`, {
                    headers: {
                        'Authorization': `Bearer ${adminToken}`
                    }
                });
                
                log(`历史API响应状态: ${response.status}`);
                
                if (response.ok) {
                    const result = await response.json();
                    const historyCount = result.data.history ? result.data.history.length : 0;
                    log(`获取处理历史成功: 共${historyCount}条记录`, 'success');
                    
                    if (historyCount > 0) {
                        result.data.history.forEach((record, index) => {
                            log(`  ${index + 1}. ${record.action_text} - ${record.admin_name} (${record.formatted_time})`);
                        });
                    }
                } else {
                    const errorText = await response.text();
                    log(`获取历史失败: ${response.status} - ${errorText}`, 'error');
                }
                
            } catch (error) {
                log(`历史查看错误: ${error.message}`, 'error');
            }
        }
        
        // 测试获取列表
        async function testList() {
            try {
                log('开始测试获取列表...');
                
                if (!adminToken) {
                    log('请先登录', 'error');
                    return;
                }
                
                const response = await fetch('/api/admin/clues?page=1&page_size=5', {
                    headers: {
                        'Authorization': `Bearer ${adminToken}`
                    }
                });
                
                log(`列表API响应状态: ${response.status}`);
                
                if (response.ok) {
                    const result = await response.json();
                    const clueCount = result.data.list ? result.data.list.length : 0;
                    log(`获取线索列表成功: 共${clueCount}条记录`, 'success');
                    
                    if (clueCount > 0) {
                        result.data.list.forEach((clue, index) => {
                            log(`  ${index + 1}. ${clue.clue_no} - ${clue.title} (${clue.status})`);
                        });
                    }
                } else {
                    const errorText = await response.text();
                    log(`获取列表失败: ${response.status} - ${errorText}`, 'error');
                }
                
            } catch (error) {
                log(`列表获取错误: ${error.message}`, 'error');
            }
        }
        
        // 页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            log('页面加载完成');
            
            // 检查是否已有token
            const savedToken = localStorage.getItem('adminToken');
            if (savedToken) {
                adminToken = savedToken;
                log('发现已保存的登录状态');
                document.getElementById('loginStatus').innerHTML = '<span class="text-success">✅ 已登录</span>';
                document.getElementById('testExportBtn').disabled = false;
                document.getElementById('testDetailBtn').disabled = false;
                document.getElementById('testHistoryBtn').disabled = false;
                document.getElementById('testListBtn').disabled = false;
            }
            
            // 绑定事件
            document.getElementById('loginBtn').addEventListener('click', login);
            document.getElementById('testExportBtn').addEventListener('click', testExport);
            document.getElementById('testDetailBtn').addEventListener('click', testDetail);
            document.getElementById('testHistoryBtn').addEventListener('click', testHistory);
            document.getElementById('testListBtn').addEventListener('click', testList);
            document.getElementById('clearLogBtn').addEventListener('click', clearLog);
            
            log('事件绑定完成');
        });
    </script>
</body>
</html> 